package com.project.basis.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ECLAIR on 2018/3/21.
 */
public class JsonUtils {

    private static Gson gson = null;

    static {
        if (gson == null) {
            gson = new Gson();
        }
    }

    /**
     * json 转化为JavaBean
     *
     * @param jsonStr Json字符串
     * @param cl      类名
     */
    public static Object jsonToBean(String jsonStr, Class<?> cl) {
        Object obj = null;
        try {
            if (gson != null) {
                obj = gson.fromJson(jsonStr, cl);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * @param json
     * @param clazz
     * @return
     */
    public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjects = gson.fromJson(json, type);
        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
            arrayList.add(gson.fromJson(jsonObject, clazz));
        }
        return arrayList;
    }

    /**
     * @return
     */
    public static String beanToJson(Object obj) {
        String json = null;
        try {
            if (gson != null) {
                json = gson.toJson(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * @return
     */
    public static <T> String listToJson(List<T> obj) {
        String json = null;
        try {
            if (gson != null) {
                json = gson.toJson(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
}
